<?php

class LoginForm extends UserForm
{

    public function configure()
    {
        parent::configure();
        $this->userObject = null;
        $this->useFields(array('username', 'password'));
        $this->getValidatorSchema()->setPostValidator(
                new sfValidatorCallback(array('callback' => array($this, 'checkLoginData')))
        );
    }

    public function checkLoginData($validator, $values)
    {
        $flag = false;
        if ($values['username'] && $values['password'])
        {
            $user = UserTable::getInstance()->findOneByUsername($values['username']);
            if ($user)
            {
                if ($user->getPassword() == User::encrypt($values['password'], $user->getToken()))
                {
                    $this->userObject = $user;
                    $flag = true;
                }
            }
        }
        if (!$flag)
        {
            // password is not correct, throw an error
            throw new sfValidatorError($validator, 'invalid username and password');
        }
        // password is correct, return the clean values
        return $values;
    }

    /**
     *
     * @return User  
     */
    public function getUserObject()
    {
        return $this->userObject;
    }

}